package com.example.tree.service.impl;

import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Set;

@Service
@RequiredArgsConstructor
public class BloomFilterService {
    private final RedissonClient redissonClient;
    private final RedisTemplate<String, Object> redisTemplate;
    private final String BLOOM_FILTER_NAME = "tree_bloom_filter";

    private RBloomFilter<String> getCurrentFilter() {
        return redissonClient.getBloomFilter(BLOOM_FILTER_NAME); 
    }

    // 初始化布隆过滤器
    @PostConstruct
    public void init() {
        RBloomFilter<String> filter = getCurrentFilter();
        if (!filter.isExists())  {
            filter.tryInit(500000L,  0.01); // 预期50万数据，1%误判率 
            warmUpFilter(filter);
        }
    }
 
    // 预热数据
    private void warmUpFilter(RBloomFilter<String> filter) {
        Set<String> keys = redisTemplate.keys("product:*");
        if (keys != null) {
            keys.forEach(filter::add); 
        }
    }
 
    // 双写方法（关键实现）
    public void addKey(String key) {
        // 写入Redis
        redisTemplate.opsForValue().set(key,  "some_value");
        
        //
        RBloomFilter<String> current = getCurrentFilter();

        current.add(key); 

    }
 
    // 检查是否存在
    public boolean mightContain(String key) {
        return getCurrentFilter().contains(key);
    }
}